<script lang="ts" setup>
import { ContactApi } from '~/api/ContactApi'
import { JobRecordApi } from '~/api/JobRecordApi'
import LxButton from '~/components/common/LxButton.vue'
import PairsView from '~/components/common/PairsView.vue'
import { ContactModel, JobRecordModel } from '~/model'
import { SalaryModel } from '~/model/SalaryModel'
import { ScheduleModel } from '~/model/ScheduleModel'
import JobRecordGroup from '~/components/job/RecordGroup.vue'
import { lodash } from '~/utils'
import moment from 'moment'

const route = useRoute()
const router = useRouter()

const id = ref(0)
const worker = ref(new ContactModel())
const records = ref([] as JobRecordModel[])
const salaryModel = computed(() => {
  const groups = SalaryModel.divideHistoryGroups(records.value)
  return lodash.last(groups)!
})
// setTimeout(() => {
//   const groups = SalaryModel.divideHistoryGroups(records.value)
// }, 2000)
const scheduleModel = computed(() => {
  return records.value.length ? new ScheduleModel(records.value) : null
})

// 增加了排期的具体工作时段显示
const scheduleDetail = computed(() => {
  const _x = scheduleModel.value?.getSchedule()
  if (_x === '白班') {
    return '白班(8:00~20:00)'
  }
  else if (_x === '夜班') {
    return '夜班(20:00~次日8:00)'
  }
  else {
    return _x
  }
})

onMounted(() => {
  id.value = Number.parseInt(route.query.id as string)
  ContactApi.getAll()
    .then((res) => {
      worker.value = res.find(x => x.id === id.value)!
    })
  JobRecordApi.getAll()
    .then((res) => {
      const ret = res.filter(x => x.worker!.id === id.value)

      // console.log('?');
      // console.log(ret.map(x => x.date.valueOf()));

      ret.sort((a, b) => b.date.valueOf() - a.date.valueOf())
      records.value = ret
      JobRecordModel.sort(records.value, true)
    })
})


function goEvent() {
  router.push(`/jobs/events/detail?event=1&worker=${worker.value.id}`)
}

function goContact() {
  router.push(`/contacts/detail?id=${id.value}`)
}

const avatar = computed(() => {
  if (!worker.value.avatar) {
    return undefined
  }
  else if (location.href.includes('localhost')) {
    // return "http://127.0.0.1:8000/media/avatar/9.jpg"
    const tail = worker.value.avatar?.match(/\/media.*/)![0]
    return `http://10.8.0.1:8000${tail}`
  }
  else {
    return worker.value.avatar
  }
})

const historyGroups = computed(() => {
  // const gs = salaryModel.value.historyGroups()
  const gs = SalaryModel.divideHistoryGroups(records.value).map(x => x.getRecords())
  gs.reverse()
  return gs
})

/** 对于白班夜班的，到下班时间工资已经计入的提示 */
const counted = computed(() => {
  // 今天0点
  const now0h = (() => {
    const t = new Date()
    t.setHours(0)
    t.setMinutes(0)
    t.setSeconds(0)
    t.setMilliseconds(0)
    return t.valueOf() / 1000
  })();
  const now = (new Date()).valueOf() / 1000
  const yesterdayStr = moment((new Date()).valueOf() - 86400000).format('MM/DD')
  const todayStr = moment().format('MM/DD')
  if (scheduleModel.value?.getSchedule() === '白班') {
    if (now - now0h > 20 * 3600) {
      return `${todayStr} 已计入`
    }
    else {
      return `${todayStr} 未计入`
    }
  }
  else if (scheduleModel.value?.getSchedule() === '夜班') {
    if (now - now0h < 8 * 3600) {
      return `${yesterdayStr} 未计入`
    }
    else if (now - now0h > 20 * 3600) {
      return `${todayStr} 未计入`
    }
    else {
      return `${yesterdayStr} 已计入`
    }
  }
  else {
    return ''
  }
})
const countedStyle = computed(() => {
  return {
    color: counted.value.includes('已计入') ? 'green' : 'gray'
  }
})
</script>

<template>
  <div of-auto id="vablbvarbhalba">
    <div flex mt2>
      <div paper w0 flex-basis-0 flex-grow-1 mx2 flex flex-col justify-center>
        <div>
          <img v-if="avatar" :src="avatar" h-4rem block mx-auto>
          <div v-else text-center text-size-3 text-gray-5>无照片</div>
        </div>
        <div text-center>{{ worker.name }}</div>
      </div>
      <!-- <div paper flex-basis-0 flex-grow-2 mr2 flex items-center>
        <PairsView w-full
          v-if="worker.id && records.length"
          :pairs="[
            ['月薪', salaryModel.currentMonthlySalary().toString()],
            ['排班', scheduleDetail],
          ]"
        />
      </div> -->
      <div paper p0 w0 flex-basis-0 flex-grow-2 mr2 flex flex-col justify-center>
        <div flex px4 py2 b-b="1px solid gray-3">
          <div text-gray-5>月薪</div>
          <div ml-auto>{{ salaryModel.currentMonthlySalary().toString() }}</div>
        </div>
        <div flex px4 py2>
          <div text-gray-5>排班</div>
          <div ml-auto>{{ scheduleDetail }}</div>
        </div>
      </div>
      
    </div>
    

    <div flex text-center>
      <div paper w0 flex-basis-0 flex-grow-1 mx2 flex flex-col justify-center>
        <div text-gray-5 text-size-3.5>工作天数</div>
        <div text-size-5 my2>{{ salaryModel.totalWorkDays().toString() }}</div>
        <div text-gray-5 text-size-3 :style="countedStyle">{{ counted }}</div>
      </div>
      <div paper p0 w0 flex-basis-0 flex-grow-2 mr2>
        <div b-b="1px solid gray-3" p2>
          <div text-gray-5 text-size-3.5>薪资总计</div>
          <div text-size-5>{{ salaryModel.totalShouldSent().toString() }}</div>
        </div>
        <div flex>
          <div flex-1 p2 b-r="1px solid gray-3">
            <div text-gray-5 text-size-3.5>已发</div>
            <div text-size-5>{{ salaryModel.totalAdvance().toString() }}</div>
          </div>
          <div flex-1 p2>
            <div text-gray-5 text-size-3.5>未发</div>
            <div text-size-5>{{ salaryModel.totalShouldSentRemaining().toString() }}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- <div flex text-center>
      <div paper flex-1 mr2>
        <div text-gray-5 text-size-3.5>薪资总计</div>
        <div text-size-5 mt2>{{ salaryModel.totalShouldSent().toString() }}</div>
      </div>
      <div paper flex-1 mr2>
        <div text-gray-5 text-size-3.5>已发</div>
        <div text-size-5 mt2>{{ salaryModel.totalAdvance().toString() }}</div>
      </div>
      <div paper flex-1 mr2>
        <div text-gray-5 text-size-3.5>未发</div>
        <div text-size-5 mt2>{{ salaryModel.totalShouldSentRemaining().toString() }}</div>
      </div>
    </div> -->

    <!-- <PairsView
      v-if="worker.id && records.length"
      :pairs="[
        ['工作天数', salaryModel.totalWorkDays().toString()],
        ['薪资总计', salaryModel.totalShouldSent().toString()],
        ['已发', salaryModel.totalAdvance().toString()],
        ['未发', salaryModel.totalShouldSentRemaining().toString()],
      ]"
    /> -->

    <div mx2 mb2 flex>
      <LxButton title="创建事务" color="mediumseagreen" icon="plus" :action="goEvent" />
      <LxButton title="联系" :action="goContact" color="darkorange" icon="phone" />

    </div>

    <JobRecordGroup
      v-for="(jrGroup, index) in historyGroups"
      :key="index"
      :jobRecords="jrGroup"/>
    
  </div>
</template>

<route lang="yaml">
meta:
  title: 工人详情
</route>

<style scoped>
#vablbvarbhalba > div {
  box-sizing: border-box;
}
</style>
